local redis = require "redisutil"
local cjson = require "cjson"
local http = require "resty.http"
local function handlecloudfirequest()

   local requestip = ngx.var.remote_addr;
   if(ngx.var.arg_realip ~= nil) then
      requestip = ngx.var.arg_realip
   end 
   
   local mysql = require "mysqlutil"
   local curProxyInfo = {};--当前路由信息
   if(redis.testEnable() == nil) then
      ngx.say(cjson.encode({ code=405,msg="统一网关api redis 服务不可用，不能提供服务" }))
      return 
   end
   local res = redis.redkey(requestip);
   --ngx.say(requestip)
   --ngx.say(cjson.encode(res))
   if res == nil then
      local resp = {code=405,mgs="应用未配置服务器信息，不能访问"}
      ngx.say(cjson.encode(resp))
      return 

      	--[[local proxyInfo = mysql.selectProxyInfo(requestip)
         if(proxyInfo and next(proxyInfo)) then
			   curProxyInfo = proxyInfo[1]
         else
			   
         end--]]
   else
      curProxyInfo = cjson.decode(res);
   end
   if(curProxyInfo.status~=1) then
      ngx.say(cjson.encode({ code=405,msg="企业费用报销未启用" }))
      return 
   end
   --ngx.say(cjson.encode(curProxyInfo))
   --ngx.say(curProxyInfo.ekb_corp_id);
   --ngx.say(ngx.var.corpid);
   
   local corpurl = "https://" .. curProxyInfo.ekbPrefix .. ".ekuaibao.com/api/openapi/v2/location?corpId=" .. curProxyInfo.ekbCorpId
   -- local res = ngx.location.capture("/getekburl",
             -- { args = { corpId=curProxyInfo.ekbCorpId}});
   local res = get_access_token(corpurl)


   if(res.body=="企业尚未注册成功") then
      ngx.say(cjson.encode({ code=405,msg="企业尚未注册成功" }))
      return 
   else
      --企业已经注册，能够正常进行业务
      local urlpath = cjson.decode(res.body)

      if(curProxyInfo.urlPrefix ~= urlpath.value) then
         --url 已变更或是第一次获取url
         --ngx.say(urlpath.value)
         --ngx.say("结尾字符是" .. string.byte(urlpath.value,-1))
         if(string.byte(urlpath.value,-1) ~= 47)then
            curProxyInfo.urlPrefix = urlpath.value.. "/";
         else
            curProxyInfo.urlPrefix = urlpath.value;
         end   
      end
      if(curProxyInfo.tokenInfo == nil) then
         --token 不存在，访问获取token
         local TOKEN_API_REL_URL = "api/openapi/v1/auth/"

         curProxyInfo.powerCode = curProxyInfo.powerCode or "default"
         local TOKEN_API_ARG = "$" .. curProxyInfo.vertifyCode .. "?powerCode=" .. curProxyInfo.powerCode
         local powerEntity = {powerCode = curProxyInfo.powerCode}
         -- ngx.say(ngx.encode_args(powerEntity))
         
         
         local res = sendEKBRequest("POST",curProxyInfo.urlPrefix,TOKEN_API_REL_URL .. TOKEN_API_ARG,ngx.encode_args(powerEntity))
         --ngx.say(curProxyInfo.urlPrefix .. TOKEN_API_REL_URL .. TOKEN_API_ARG)
         --ngx.say(res.body)
         --[[ngx.say(curProxyInfo.urlPrefix .. "***" )
         ngx.say( TOKEN_API_REL_URL .. "***" )
         ngx.say(TOKEN_API_ARG .. "***")--]]
         local ok , tokendata = pcall(cjson.decode,res.body)
         -- return
         if not ok then
            ngx.say(cjson.encode({ code=405,msg="获取授权时，验证码已失效" }))
            return 
         else
            curProxyInfo.tokenInfo = tokendata.value;
            redis.setvalue(requestip,cjson.encode(curProxyInfo))
            --ngx.say(cjson.encode(tokendata.value))
         end
         --ngx.say(cjson.encode(res.body))
      end

      --ngx.say(urlpath.value);
      --执行业务

      if(ngx.req.get_method()=="GET") then
         local relativeUrl = ngx.var.request_uri
         relativeUrl = string.sub(relativeUrl,11)
         --ngx.say(relativeUrl)
         local ekbargs = {powerCode = curProxyInfo.powerCode, accessToken = curProxyInfo.tokenInfo.accessToken}
         local startIndex,endIndex = string.find(relativeUrl,"?")
         if(startIndex == nil and endIndex == nil) then
            
            relativeUrl = relativeUrl .. "?" .. ngx.encode_args(ekbargs)
         else
            relativeUrl = relativeUrl .. "&" .. ngx.encode_args(ekbargs)
         end

         local res = sendEKBRequest("GET",curProxyInfo.urlPrefix,relativeUrl)
         
         --ngx.say(startIndex,endIndex)
         --ngx.say(curProxyInfo.urlPrefix,relativeUrl)
         --ngx.say(ngx.escape_uri(curProxyInfo.urlPrefix .. relativeUrl))
         
         ngx.say(res.body)
      else
         ngx.say(cjson.encode({ code=405,msg="目前仅支持易快报GET请求代理" }))
         return 
      end
      

   end
end
function sendEKBRequest(sendMethod,urlPrefix,relativeUrl,param)
    local httpc = http.new()
    if(sendMethod == "GET") then
      local res,err = httpc:request_uri(urlPrefix .. relativeUrl, {
        method = "GET",
        headers = {
            ["Accept-Encoding"] = "utf-8",
        }
      })
      return res
    else
      local res,err = httpc:request_uri(urlPrefix .. relativeUrl, {
        method = "POST",
        body = param,
        headers = {
            ["Accept-Encoding"] = "utf-8",
        }
      })
      return res
    end
    
    httpc:set_keepalive(60)
    return res
end
function get_access_token(url)
    local httpc = http.new()
    local res,err = httpc:request_uri(url, {
        method = "GET",
        headers = {
            ["Accept-Encoding"] = "utf-8",
        }
    })
    print(err)
    httpc:set_keepalive(60)
    return res
end
handlecloudfirequest();